import sys
import socket
import cv2
import numpy as np
import time
import numpy
import math

 
def SendVideo():

#     address = ('192.168.43.175', 6666)
#     try:
#         sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#         sock.connect(address)
#     except socket.error as msg:
#         print(msg)
#         sys.exit(1)

    red_lower = np.array([0,128,46])
    red_upper = np.array([400,255,255]) #设置颜色区间
    encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),100]
    last_dir = 1
    last_X = 263
    last_stamp = 0
 
    capture = cv2.VideoCapture(0)
    
 
    while 1:
        ret, frame = capture.read()
        timestamp = capture.get(cv2.CAP_PROP_POS_MSEC)
        

        b_chn,g_chn,r_chn = cv2.split(frame)
        mask = abs(100 + r_chn - g_chn)
        ret, thresh = cv2.threshold(mask, 110, 255, cv2.THRESH_BINARY)
        cnts = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[-2] #边缘检测
        if len(cnts) >0 : #通过边缘检测来确定所识别物体的位置信息得到相对坐标
            cnt = max(cnts,key=cv2.contourArea)
            (x, y, w, h) = cv2.boundingRect(cnt)
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)
            centre_X = x+w/2
            
            if centre_X-last_X<0:dir_rt = -1
            if centre_X-last_X>0:dir_rt = 1
            last_X = centre_X
            
            if last_dir != dir_rt:
                deltaT = timestamp - last_stamp
                last_stamp = timestamp
                last_dir = dir_rt
                
	T += deltaT*2
	N=0
	N += N+1
	Ta = T/N
	g = 0.00980665
	pi = 3.1415926
	l = Ta**2*g/4*pi**2

            #cv2.putText(frame, str(int(deltaT)), (10,50),cv2.FONT_HERSHEY_SIMPLEX,1.2,(0,0,255),2)
            cv2.putText(frame, str(int(l)), (10,50),cv2.FONT_HERSHEY_SIMPLEX,1.2,(0,0,255),2)
       
        else:
            time.sleep(0.01)
        cv2.imshow('frame',frame) #将具体的测试效果显示出来

#         result, imgencode = cv2.imencode('.jpg', frame, encode_param)
#         data = numpy.array(imgencode)
#         stringData = data.tostring()
#         
#         sock.send(str.encode(str(len(stringData)).ljust(16)));
#         sock.send(stringData);

        if cv2.waitKey(10) == 27:
            break

#     sock.close()
    capture.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    SendVideo()










 


